package com.smartfast4j.manager.common.listener;

import com.smartfast4j.common.Constants;
import com.smartfast4j.common.component.cache.CacheService;
import com.smartfast4j.common.config.Cachekey;
import com.smartfast4j.common.util.RSAUtils;
import com.smartfast4j.common.util.RandomUtils;
import com.smartfast4j.manager.modules.sys.service.*;
import com.smartfast4j.pojo.sys.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.List;

/**
 * 执行初始化操作
 */
@Order(value=2) //可以通过指定@Order的值来控制启动的顺序，值越小表示越先执行
@Component
public class CommandLineRunnerListener implements CommandLineRunner {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommandLineRunnerListener.class);

    @Autowired
    private CacheService cacheService;

    @Autowired
    private SysResourceService sysResourceService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysResourcePermissionService resourcePermissionService;

    @Override
    public void run(String... strings) throws Exception {
        LOGGER.debug("执行初始化操作：currentThread="+Thread.currentThread().getId());
        createAesSecretKey();
        List<SysResourcePermission> sysResourcePermissions = resourcePermissionService.init();
        //createRsaSecretKey();
        cacheResourcePermission(sysResourcePermissions);//缓存系统资源的访问权限到缓存
        loadSysUser();//加载系统用户
        loadSysRole();//加载系统角色
    }

    /**
     * 生成16位的AES加密密钥
     */
    private void createAesSecretKey(){
        //生成16位AES加密密钥
        String aesSecretKey = RandomUtils.generateMixString(16);
        //将密钥存放到缓存中
        cacheService.set(Constants.SECURITY.RSA_PRIVATE_KEY,aesSecretKey);
    }

    /**
     * 生成RSA加密秘钥
     */
    private void createRsaSecretKey(){
        //RSA公钥
        RSAPublicKey rsaPublicKey = RSAUtils.getDefaultPublicKey();
        //RSA私钥
        RSAPrivateKey rsaPrivateKey = RSAUtils.getDefaultPrivateKey();
        //将密钥存放到缓存中
        cacheService.set(Constants.SECURITY.RSA_PUBLIC_KEY,rsaPublicKey);
        cacheService.set(Constants.SECURITY.RSA_PRIVATE_KEY,rsaPrivateKey);
    }

    /**
     *
     * 缓存资源的访问权限
     */
    private void cacheResourcePermission(List<SysResourcePermission> sysResourcePermissions){
        if(CollectionUtils.isNotEmpty(sysResourcePermissions)){
            sysResourcePermissions.forEach(item-> cacheService.set(item.getRequestUrl(),item.getPerms()));
        }
    }

    /**
     * 加载系统用户
     */
    private void loadSysUser(){
        SysUserExample userExample = new SysUserExample();
        userExample.createCriteria()
                .andDeleteFlagEqualTo(Constants.DELETE_FLAG.NO);
        List<SysUser> sysUserList = sysUserService.selectByExample(userExample);
        for(SysUser sysUser:sysUserList){
            cacheService.set(Cachekey.Sys.USER+sysUser.getId(),sysUser);
        }
    }

    /**
     * 加载系统角色
     */
    private void loadSysRole(){
        SysRoleExample sysRoleExample = new SysRoleExample();
        sysRoleExample.createCriteria()
                .andDeleteFlagEqualTo(Constants.DELETE_FLAG.NO);
        List<SysRole> sysRoleList = sysRoleService.selectByExample(sysRoleExample);
        for(SysRole sysRole:sysRoleList){
            cacheService.set(Cachekey.Sys.ROLE+sysRole.getId(),sysRole);
        }
    }

}
